package com.sfx.messagequeue.common.utils;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 序列化工具
 * User: sfx
 * Date: 2023-08-01
 * Time: 20:02
 */
public class BinaryPool {
    //将对象转换成二进制字节数组

    /**
     * 把对象写入到字节流中,然后将字节流转化为对象
     * @param bean
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(Object bean) throws IOException {
        //ByteArrayOutputStream就相当于是一个变长字节数组
        try(ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();) {
            try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(arrayOutputStream) ) {
                //通过objectOutputStream.write就可以把对象写入到ObjectOutputStream流中
                //进而写入到ByteArrayOutputStream中
                objectOutputStream.writeObject(bean);
            }
            //通过ByteArrayOutputStream 转换成字节数组返回
            return arrayOutputStream.toByteArray();
        }
    }

    //将字节数组转化为Java 对象

    /**
     * 将对象放到字节流中,读取字节流转换为对象
     * @param bytes
     * @return
     */
    public static Object toJavaBean(byte[] bytes) throws IOException, ClassNotFoundException {
        Object bean = null;
        //ByteArrayOutputStream就相当于是一个变长字节数组
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);) {
            try(ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream) ) {
                //ObjectInputStream.write就可以把对象读取到到ObjectInputStream流中
                //进而读取到ByteArrayOutputStream中,进而读取到字节数组中,转换成Java对象返回
                bean =  objectInputStream.readObject();
            }
        }
        return bean;
    }
}